
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>

typedef struct ngx_http_filter_conf_s{
	ngx_flag_t enable;
} ngx_http_filter_conf_t;

/*
	header
*/

static ngx_str_t prefix = ngx_string("<h2> LiangWu </h2>");

static ngx_http_output_header_filter_pt  ngx_http_next_header_filter;
static ngx_http_output_body_filter_pt    ngx_http_next_body_filter;

ngx_command_t ngx_http_filter_commands[] = {
	{
		ngx_string("ngx_http_filter_endable"),
		NGX_HTTP_LOC_CONF | NGX_CONF_FLAG,
		ngx_conf_set_flag_slot,
		NGX_HTTP_LOC_CONF_OFFSET,
		offsetof(ngx_http_filter_conf_t, enable),
		NULL
	},
	ngx_null_command
};


static ngx_int_t ngx_http_filter_header_filter(ngx_http_request_t *r)
{
	if (r->headers_out.status != NGX_HTTP_OK) {
		return ngx_http_top_header_filter(r);
	}
	
	r->headers_out.content_length_n += prefix.len;

	return ngx_http_next_header_filter(r);
}


/// @param chain 响应体数据，是以链表的形式存储
static ngx_int_t ngx_http_filter_body_filter(ngx_http_request_t *r, ngx_chain_t *chain)
{
	ngx_buf_t *buf = ngx_create_temp_buf(r->pool, prefix.len);
	buf->start = buf->pos = prefix.data;
	buf->last = buf->pos + prefix.len;

	ngx_chain_t *ch = ngx_alloc_chain_link(r->pool);
	ch->buf = buf;
	ch->next = chain;

	return ngx_http_next_body_filter(r, ch);
}

ngx_int_t ngx_http_filter_init(ngx_conf_t *cf)
{
	ngx_http_next_header_filter = ngx_http_top_header_filter;
	ngx_http_top_header_filter  = ngx_http_filter_header_filter;
	ngx_http_next_body_filter = ngx_http_top_body_filter;
	ngx_http_top_body_filter  = ngx_http_filter_body_filter;
	return NGX_OK;
}


void *ngx_http_filter_create_loc_conf(ngx_conf_t *cf)
{
	ngx_http_filter_conf_t *conf = ngx_palloc(cf->pool, sizeof(ngx_http_filter_conf_t));
	if (conf == NULL) return NULL;

	conf->enable = NGX_CONF_UNSET;
	printf("ngx_http_filter_create_loc_conf\n");

	return conf;
}


char *ngx_http_filter_merge_loc_conf(ngx_conf_t *cf, void *prev, void *conf)
{
	return NULL;
}

ngx_http_module_t ngx_http_filter_module_ctx = {
	NULL,
	ngx_http_filter_init,

	NULL,
	NULL,

	NULL,
	NULL,

	ngx_http_filter_create_loc_conf,
	ngx_http_filter_merge_loc_conf
};




ngx_module_t ngx_http_filter_module = {
	NGX_MODULE_V1,
	&ngx_http_filter_module_ctx,
	ngx_http_filter_commands,
	NGX_HTTP_MODULE,
	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	NGX_MODULE_V1_PADDING
};